import tools from 'libs/common/tools.js'

const fullZero = (num) => {
  return num < 10 ? '0' + num : num
}

const max = arr => {
  let arrClone = arr.concat();
  arrClone.filter((v) => v != '')
  return Math.max.apply(null, arrClone)
};
const min = arr => {
  let arrClone = arr.concat();
  arrClone = arr.filter((v) => v != '')
  return Math.min.apply(null, arrClone)
}

// 获取x轴时间数据
const getDate = (fmt, len) => {
  let d = new Date()
  let res = []
  let a;
  for (let i = 0; i < len; i++) {
    switch (fmt) {
      case 'yyyyMMdd':
        a = `${d.getFullYear()}${fullZero(d.getMonth() + 1)}${fullZero(d.getDate())}`;
        break;
      case 'MM.dd':
        a = `${fullZero(d.getMonth() + 1)}.${fullZero(d.getDate())}`;
        break;
    }
    res.unshift(a)
    d = new Date(d.getTime() - 1000 * 60 * 60 * 24)
  }
  return res
};

// 异常数据检测方法
const abnDataDetect = (arr, lastIndex) => {
  let max = max(arr);
  let min = min(arr);
  let diffVal = (max - lastIndex) > (lastIndex - min) ? (max - lastIndex) : (lastIndex - min);
  if (diffVal > lastIndex / 50) {
    return {
      haveOutliers: true,
      value: (Math.floor(diffVal / lastIndex * 100 / 5) + 1) * 5
    }
  } else {
    return {
      haveOutliers: false,
      value: null
    }
  }
};

// 分钟刷新
let refPerMinute = {
  init: function(handle) {
    handle();
    const entryTime = new Date();  // 进入页面时间
    if (!verifyTime(entryTime)) return;  // 验证 进入页面时间 hh:mm   不在开盘时间内 不执行
    let tmpTime = entryTime.getTime();
    this.timer = setInterval(() => {
      if (!verifyTime(new Date(tmpTime += 60000))) return;
      console.log(new Date(tmpTime));
      handle();
    }, 60000)
  },
  destory: function() {
    clearInterval(this.timer)
  }
};

// 验证时间
const verifyTime = (val) => {
  let tmp = `${fullZero(val.getHours())}:${fullZero(val.getMinutes())}`;
  return tmp >= '09:30' && tmp <= '11:30' || tmp >= '13:00' && tmp <= '15:00'
};

// option对象属性的深拷贝
const extend = (initalObj, finalObj) => {
  if (finalObj == {}) {
    return initalObj;
  } else {
    for (let i in initalObj) {
      if (finalObj[i] == undefined) {
        finalObj[i] = initalObj[i]
      } else if (typeof initalObj[i] == 'object') {
        extend(initalObj[i], finalObj[i])
      }
    }
    return finalObj;
  }
};
const getNowTime = () => {
  let date = new Date();
  let str = '';
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month < 10 ? '0' + month : month;
  let day = date.getDate();
  day = day < 10 ? '0' + day : day;
  str += year += month += day;
  return str;
}

//  获取总览页大盘时间数据
const getTradeTimeArr = () => {
  let resultArr = [],
    dateTmp = new Date(2000, 1, 1, 9, 30);

  resultArr.push(tools.DateFormat(dateTmp, 'HH:mm'));
  for (let i = 0; i < 120; i++) {
    dateTmp.setMinutes(dateTmp.getMinutes() + 1);
    resultArr.push(tools.DateFormat(dateTmp, 'HH:mm') == '11:30' ? '11:30/13:00' : tools.DateFormat(dateTmp, 'HH:mm'));
  }

  dateTmp = new Date(2000, 1, 1, 13, 1);
  resultArr.push(tools.DateFormat(dateTmp, 'HH:mm'));
  for (let i = 0; i < 119; i++) {
    dateTmp.setMinutes(dateTmp.getMinutes() + 1);
    resultArr.push(tools.DateFormat(dateTmp, 'HH:mm'));
  }
  return resultArr;
};

const getIndexMaxChg = data => {
  const range = max([Math.abs(max(data.index)) - data.closing, Math.abs(min(data.index) - data.closing)]) * 1.2;
  const chgRng = (range / data.closing * 100).toFixed(2);

  return chgRng
}

/** 大数据格式化，显示为万／亿  start**/
const decimal = decimal => num => num.toFixed(decimal);

const decimal0 = num => parseInt(num);

const decimal1 = decimal(1);

const decimal2 = decimal(2);

// 解析长数据
const destruct = number => {
  if (isNaN(number)) {
    return {
      isNegative: false,
      num: '',
      unit: ''
    }
  }
  const isNegative = number < 0;
  const num = Math.abs(number);
  const l = parseInt(num).toString().length;

  return {
    isNegative,
    num: l < 5 ? decimal0(num)
      : l < 7 ? decimal2(num / 10000)
      : l < 8 ? decimal1(num / 10000)
      : l < 9 ? decimal0(num / 10000)
      : l < 11 ? decimal2(num / 100000000)
      : l < 12 ? decimal1(num / 100000000)
      : decimal0(num / 100000000),
    unit: l < 5 ? '' : l < 9 ? '万' : '亿'
  }
}
/** 大数据格式化，显示为万／亿  end**/

/** 转换1013接口数据 ****/
const fillZero = num => num < 10 ? '0' + num : num;
const timeFromMinuts = m => {
  let d = new Date(new Date(2000, 0, 1, 0, 0).getTime() + m * 60 * 1000);
  return `${fillZero(d.getHours())}:${fillZero(d.getMinutes())}`;
};
/** 转换1013接口数据 ****/
const transform1013 = (data, isLargeOrder) => {
  let netNumber = [],
    mIn = [],
    mOut = [],
    mNetNumber = [],
    xTime = [];
  // console.log(data.TableInfo = data.TableInfo.slice(79, 235), indexXDate.length)

  data.TableInfo.forEach(item => {
    let tmpDate = timeFromMinuts(item.Minute);
    if (tmpDate >= '09:30' && tmpDate <= '11:30' || tmpDate >= '13:01' && tmpDate <= '15:00') {
      tmpDate = tmpDate == '11:30' ? '11:30/13:00' : tmpDate
      xTime.push(tmpDate)
      netNumber.push([tmpDate, isLargeOrder ? item.ddljjlr : item.ljjlr]);
      mIn.push([tmpDate, isLargeOrder ? item.bbmoney : item.bmoney]);
      mOut.push([tmpDate, isLargeOrder ? -item.sbmoney : -item.smoney]);
      mNetNumber.push([tmpDate, isLargeOrder ? -item.ddjlr : item.jlr])
    }
  });
  if (netNumber.length == 0) {
    let tmpDate = '09:30'
    xTime.push(tmpDate);
    netNumber.push([tmpDate, 0]);
    mIn.push([tmpDate, 0]);
    mOut.push([tmpDate, 0]);
    mNetNumber.push([tmpDate, 0])
  }
  return {
    xTime: xTime,
    netNumber: netNumber,
    minute: {
      in: mIn,
      out: mOut,
      mNetNumber: mNetNumber
    }
  }
}
// 1015接口数据处理
const transform1015 = intoUnderlying => {
  let list = [];
  intoUnderlying.TableInfo.forEach((item, index) => {
    if (index >= 10) return;
    list.push({
      strName: item.stockname,
      strCode: item.stock,
      netFlowIn: item.jlr,
      nAmount: item.zd,
      nRate: item.zdf,
      nPrice: item.Match
    })
  });
  return list;
};

// ChartOverlap组件数据处理
const FIELD_ENUM = [
  {
    B_MONEY: 'bmoney',
    S_MONEY: 'smoney',
    JLR: 'jlr'
  },
  {
    B_MONEY: 'ljbbmoney',
    S_MONEY: 'ljsbmoney',
    JLR: 'ddljjlr'
  }
];
const overlapProcess = (fund, index, type) => {
  let bmoney = [];
  let smoney = [];
  let netNumber = [];
  let indexData = [];

  let fundDate = fund.TableInfo.map(item => item.date);
  let indexDate = index.TableInfo.map(item => item.date);
  let indexMoreData = indexDate.length >= fundDate.length;

  fund.TableInfo.forEach((item, index) => {
    bmoney.push(item[FIELD_ENUM[type].B_MONEY]);
    smoney.push(-item[FIELD_ENUM[type].S_MONEY]);
    netNumber.push(item[FIELD_ENUM[type].JLR])
  });

  for (let item of index.TableInfo) {
    indexData.push(item.price)
  }

  let arr = [];
  let arr2 = [];
  let arr3 = [];
  let arr4 = [];

  if (indexMoreData) {      // 指数数据更多
    arr4 = indexData;
    indexDate.forEach((i, indexA) => {
      if (fundDate.indexOf(i) == -1) {
        arr[indexA] = arr2[indexA] = arr3[indexA] = '';
      } else {
        arr[indexA] = bmoney[fundDate.indexOf(i)];
        arr2[indexA] = smoney[fundDate.indexOf(i)];
        arr3[indexA] = netNumber[fundDate.indexOf(i)];
      }
    })
  } else {
    arr = bmoney;
    arr2 = smoney;
    arr3 = netNumber;
    fundDate.forEach((i, indexB) => {
      if (indexDate.indexOf(i) == -1) {
        arr4[indexB] = '';
      } else {
        arr4[indexB] = indexData[indexDate.indexOf(i)]
      }
    })
  }
  return {
    xTime: indexMoreData ? indexDate : fundDate,
    in: arr,
    out: arr2,
    netNumber: arr3,
    indexData: arr4
  }
}

const financeProcess = (index, fund) => {
  fund.xTime = fund.xTime.map(v => v.replace(/-/g, ''))
  index.TableInfo = index.TableInfo.filter((item) => {
    return fund.xTime.includes(item.date)
  })
  let {xTime, change, finance} = fund
  return {
    xTime,
    change,
    finance,
    shIndex: index.TableInfo.map(item => item.price)
  }
}
const getUrlParam = (name, h) => {
  var url = decodeURI(location.search); // 获取url中"?"符后的字串
  var theRequest = {};
  if (url.indexOf('?') !== -1) {
    var str = url.substr(1);
    var strs = str.split('&');
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
    }
  }
  return theRequest[name];
}

const floatAdd = (arg1, arg2) => {
  let r1 = 0;
  let r2 = 0;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) { }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) { }
  let m = Math.pow(10, Math.max(r1, r2));
  return (Math.round(arg1 * m) + Math.round(arg2 * m)) / m;
}

export {
  max,
  min,
  getDate,
  fullZero,
  extend,
  getNowTime,
  getTradeTimeArr,
  verifyTime,
  abnDataDetect,
  refPerMinute,
  getIndexMaxChg,
  destruct,
  transform1013,
  getUrlParam,
  transform1015,
  overlapProcess,
  financeProcess,
  floatAdd
}
